package com.xialuo.study.tools;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.io.FileReader;
import java.io.IOException;
import java.util.*;

@Component
public class DataAnalyzer {
    private static final Logger logger = LoggerFactory.getLogger(DataAnalyzer.class);
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 分析CSV数据文件，返回数据和元数据信息
     */
    @Tool(description = "读取CSV文件内容，解析数据并返回统计信息")
    public Map<String, Object> analyzeData(
            @ToolParam(description = "CSV数据文件的路径") String dataPath
    ) {
        try {
            logger.info("开始解析数据文件: {}", dataPath);

            // 读取和解析CSV文件
            List<CSVRecord> csvRecords = readCSVFile(dataPath);
            List<Map<String, String>> tableData = convertToTableData(csvRecords);

            // 创建包含数据和元数据的返回结构
            Map<String, Object> result = new HashMap<>();

            // 添加主数据
            result.put("data", tableData);

            // 添加元数据
            result.put("metadata", extractMetadata(csvRecords, tableData));

            // 添加数据摘要
            result.put("summary", generateDataSummary(tableData));

            logger.info("数据解析完成，共 {} 行记录", tableData.size());
            return result;
        } catch (IOException e) {
            logger.error("读取或解析数据失败", e);
            throw new RuntimeException("数据分析失败: " + e.getMessage());
        }
    }

    /**
     * 读取CSV文件
     */
    private List<CSVRecord> readCSVFile(String dataPath) throws IOException {
        try (FileReader fileReader = new FileReader(dataPath);
             CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(fileReader)) {
            return new ArrayList<>(parser.getRecords());
        }
    }

    /**
     * 将CSV记录转换为表格数据
     */
    private List<Map<String, String>> convertToTableData(List<CSVRecord> records) {
        List<Map<String, String>> tableData = new ArrayList<>();

        for (CSVRecord record : records) {
            Map<String, String> row = new LinkedHashMap<>();
            record.toMap().forEach((key, value) -> row.put(key, value));
            tableData.add(row);
        }

        return tableData;
    }

    /**
     * 提取数据元信息
     */
    private Map<String, Object> extractMetadata(List<CSVRecord> records, List<Map<String, String>> tableData) {
        Map<String, Object> metadata = new HashMap<>();

        if (tableData.isEmpty()) {
            return metadata;
        }

        // 获取列名
        List<String> columns = new ArrayList<>(tableData.get(0).keySet());
        metadata.put("columns", columns);

        // 记录行数
        metadata.put("rowCount", tableData.size());

        // 推断每列数据类型
        Map<String, String> columnTypes = new HashMap<>();
        for (String column : columns) {
            columnTypes.put(column, inferColumnType(tableData, column));
        }
        metadata.put("columnTypes", columnTypes);

        return metadata;
    }

    /**
     * 推断列的数据类型
     */
    private String inferColumnType(List<Map<String, String>> tableData, String column) {
        // 采样数据(最多10行)进行类型推断
        int sampleSize = Math.min(10, tableData.size());
        int numericCount = 0;
        int dateCount = 0;

        for (int i = 0; i < sampleSize; i++) {
            String value = tableData.get(i).get(column);
            if (value == null || value.trim().isEmpty()) {
                continue;
            }

            // 尝试解析为数字
            try {
                Double.parseDouble(value);
                numericCount++;
                continue;
            } catch (NumberFormatException ignored) {
                // 不是数字，继续检查
            }

            // 尝试解析为日期
            if (value.matches("\\d{4}[/-]\\d{1,2}[/-]\\d{1,2}") ||
                value.matches("\\d{1,2}[/-]\\d{1,2}[/-]\\d{4}")) {
                dateCount++;
            }
        }

        // 判断类型
        if (numericCount > sampleSize / 2) {
            return "numeric";
        } else if (dateCount > sampleSize / 2) {
            return "date";
        } else {
            return "string";
        }
    }

    /**
     * 生成数据摘要
     */
    private Map<String, Object> generateDataSummary(List<Map<String, String>> tableData) {
        Map<String, Object> summary = new HashMap<>();

        if (tableData.isEmpty()) {
            return summary;
        }

        // 表格大小
        summary.put("rowCount", tableData.size());
        summary.put("columnCount", tableData.get(0).size());

        // 获取列名
        List<String> columns = new ArrayList<>(tableData.get(0).keySet());

        // 样本数据 (最多10行)
        int sampleSize = Math.min(10, tableData.size());
        summary.put("sampleData", tableData.subList(0, sampleSize));

        // 缺失值统计
        Map<String, Integer> missingValues = new HashMap<>();
        for (String column : columns) {
            long missingCount = tableData.stream()
                .filter(row -> row.get(column) == null || row.get(column).trim().isEmpty())
                .count();
            if (missingCount > 0) {
                missingValues.put(column, (int) missingCount);
            }
        }
        summary.put("missingValues", missingValues);

        return summary;
    }
}
